import React, { useState } from 'react'
import {
  Button,
  Input,
  message,
  Modal,
  Pagination,
  Popconfirm,
  Table,
} from 'antd'
import { NoteQueryParams, useNotes } from '@/domain/note'
import { DeleteOutlined, EyeOutlined } from '@ant-design/icons'
import NoteContent from '@/domain/note/components/NoteContent.tsx'
import { NoteWithRelations } from '@/domain/note/types/serviceTypes.ts'
import { noteService } from '@/domain/note/service/noteService.ts'

const AdminNoteList: React.FC = () => {
  // 筛选参数状态
  const [filters, setFilters] = useState<NoteQueryParams>({
    page: 1,
    pageSize: 10,
    sort: 'create',
    order: 'desc',
  })

  // 获取笔记列表数据
  const { noteList, pagination, loading } = useNotes(filters)
  /**
   * 处理 分页变化
   * @param page 当前页码
   * @param pageSize 每页显示的条数
   */
  function handlePageChange(page: number, pageSize: number) {
    setFilters({
      ...filters,
      page,
      pageSize,
    })
  }
  // 当前选中的笔记（用于预览）
  const [currentNote, setCurrentNote] = useState<NoteWithRelations | null>(null)

  // 控制预览模态框状态
  const [isShowNote, setIsShowNote] = useState(false)

  /**
   * 删除笔记处理函数
   * @param noteId 笔记ID
   */
  const handleDelete = async (noteId: number) => {
    const resp = await noteService.deleteNoteService(noteId)
    if (!resp) {
      message.error('删除失败')
    } else {
      message.success('删除成功')
    }
  }

  /**
   * 查看笔记详情
   * @param note 笔记对象
   */
  const showNote = (note: NoteWithRelations) => {
    setCurrentNote(note)
    setIsShowNote(true)
  }

  // 表格列配置
  const columns = [
    {
      title: '作者',
      dataIndex: 'authorName',
      key: 'authorName',
      render: (_authorName: string, record: NoteWithRelations) => (
        <div>{record.author ? record.author.username : '用户已注销'}</div>
      ),
    },
    {
      title: '作者ID',
      dataIndex: 'authorId',
      key: 'authorId',
      render: (_authorId: number, record: NoteWithRelations) => (
        <div>{record.author ? record.author.userId : '用户已注销'}</div>
      ),
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      render: (_categoryName: string, record: NoteWithRelations) => (
        <div>{record.category ? record.category.categoryName : '未分类'}</div>
      ),
    },
    {
      title: '分类ID',
      dataIndex: 'categoryId',
      key: 'categoryId',
      render: (_categoryId: number, record: NoteWithRelations) => (
        <div>{record.category ? record.category.categoryId : '未分类'}</div>
      ),
    },
    {
      title: '笔记ID',
      dataIndex: 'noteId',
      key: 'noteId',
    },
    {
      title: '查看笔记',
      key: 'preview',
      render: (_: any, record: NoteWithRelations) => (
        <Button icon={<EyeOutlined />} onClick={() => showNote(record)}>
          查看
        </Button>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: NoteWithRelations) => (
        <Popconfirm
          title="确定要删除这篇笔记吗？"
          onConfirm={() => handleDelete(record.noteId)}
          okText="确定"
          cancelText="取消"
        >
          <Button danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ]

  return (
    <div className="rounded-lg bg-white p-4">
      {/* 筛选区域 */}
      <div className="mb-4 grid grid-cols-1 gap-4 md:grid-cols-4">
        <Input
          placeholder="作者ID"
          value={filters.authorId}
          onChange={(e) =>
            setFilters({
              ...filters,
              authorId: e.target.value as unknown as number,
            })
          }
        />
        <Input
          placeholder="分类ID"
          value={filters.categoryId}
          onChange={(e) =>
            setFilters({
              ...filters,
              categoryId: e.target.value as unknown as number,
            })
          }
        />
        <div className="flex gap-2">
          <Button
            type="primary"
            onClick={() => {
              setFilters({
                ...filters,
                page: 1,
              })
            }}
          >
            筛选
          </Button>
          <Button
            onClick={() => {
              setFilters({
                page: 1,
                pageSize: 10,
              })
            }}
          >
            重置
          </Button>
        </div>
      </div>

      {/* 表格 */}
      <Table
        columns={columns}
        dataSource={noteList}
        rowKey="noteId"
        pagination={false}
        className="mb-4"
        loading={loading}
      />
      {/* 笔记预览模态框 */}
      <Modal
        open={isShowNote}
        onCancel={() => setIsShowNote(false)}
        footer={null}
        width="80%"
        style={{ top: 20 }}
        bodyStyle={{ maxHeight: '80vh', overflow: 'auto' }}
      >
        {currentNote && (
          <div className="p-4">
            <NoteContent note={currentNote} />
          </div>
        )}
      </Modal>
      {/* 分页 */}
      <Pagination
        total={pagination?.total}
        current={filters.page}
        pageSize={filters.pageSize}
        onChange={handlePageChange}
        onShowSizeChange={handlePageChange}
        showSizeChanger
        pageSizeOptions={['10', '20', '50', '100']}
      />
    </div>
  )
}

export default AdminNoteList
